<template>
  <BasicModal
    title="添加成员"
    :destroy-on-close="true"
    width="40%"
    @ok="handleSubmit"
    @register="registerModal"
  >
    <BasicForm @register="register" />
  </BasicModal>
</template>
<script setup lang="ts">
  import { BasicModal, useModal } from '@/components/Modal';
  import { nextTick, ref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { defHttp } from '@/utils/http/axios';
  import { grantRole } from '@/api/sys/user';
  import { message } from 'ant-design-vue';

  const [register, { setFieldsValue, getFieldsValue }] = useForm({
    labelWidth: 80,
    showActionButtonGroup: false,
    schemas: [
      {
        field: 'roleIdList',
        label: '所属角色',
        component: 'ApiSelect' as any,
        componentProps: {
          mode: 'multiple',
          api: (params: any) => {
            return defHttp.post({ url: '/sys/role/select', params });
          },
        },
        colProps: {
          span: 24,
        },
      },
    ],
  });
  const currentRecord = ref();
  const [registerModal, { openModal, closeModal }] = useModal();
  const emits = defineEmits(['success']);
  const handleSubmit = () => {
    grantRole({
      userId: currentRecord.value.id,
      roleIdList: getFieldsValue().roleIdList || [],
    }).then(() => {
      message.success('保存成功');
      emits('success');
      closeModal();
    });
  };
  defineExpose({
    show(record) {
      currentRecord.value = record;
      openModal();
      nextTick(() => {
        setFieldsValue({
          roleIdList: record?.roleIds?.split(',') || [],
        });
      });
    },
  });
</script>
<style lang="less" scoped></style>
